package com.powernode.teatraceability.controller.plateprocessmgt;

import com.powernode.teatraceability.pojo.login.User;
import com.powernode.teatraceability.pojo.plateprocessmgt.ProductBatch;
import com.powernode.teatraceability.service.basicinfomgt.OriginService;
import com.powernode.teatraceability.service.basicinfomgt.ProductService;
import com.powernode.teatraceability.service.plateprocessmgt.ProductBatchService;
import com.powernode.teatraceability.util.GlobalConfig;
import com.powernode.teatraceability.util.JsonData;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/goods/batch")
public class ProductBatchController {

    @Resource
    private ProductBatchService productBatchService;
    @Resource
    private ProductService productService;
    @Resource
    private OriginService originService;

    @GetMapping("/{cpmc}/{pageNum}/{pageSize}")
    public JsonData selectLike(@PathVariable int pageNum,
                                  @PathVariable int pageSize,
                                  @PathVariable String cpmc,
                                  @SessionAttribute User user) {
        GlobalConfig.initPageRequest(pageNum, pageSize);
        productBatchService.selectLike(user.getQydm(),cpmc);
        return GlobalConfig.LOCAL.get();
    }

    @GetMapping("/{pageNum}/{pageSize}")
    public JsonData selectAllInfo(@PathVariable int pageNum,
                                  @PathVariable int pageSize,
                                  @SessionAttribute User user){
        GlobalConfig.initPageRequest(pageNum,pageSize);
        productBatchService.selectAllInfo(user.getQydm());
        return GlobalConfig.LOCAL.get();
    }

    @PostMapping
    public JsonData insert(@RequestBody ProductBatch productBatch,
                           @SessionAttribute User user){
        productBatch.setQydm(user.getQydm());
        productBatch.setPch(getRandomPch());
        productBatch.setCpbh(productService.queryCpbhByCpmc(productBatch.getCpmc()));
        productBatch.setCdbh(originService.queryCdbhByCdmc(productBatch.getChandi()));
        productBatchService.insert(productBatch);
        return GlobalConfig.LOCAL.get();
    }
    private String getRandomPch(){
        List<String> pchs = productBatchService.queryAllPch();
        String pch;
        do {
            pch = String.valueOf((int) (Math.random() * (int) 1e8));
        } while(pchs.indexOf(pch)!=-1 && pch.length()!=8);
        return pch;
    }
    @DeleteMapping("/{bh}")
    public JsonData delete(@PathVariable int bh){
        productBatchService.delete(bh);
        return GlobalConfig.LOCAL.get();
    }

}
